<template>
  <div>
    <div v-for="item in state.fileList" :key="item.uid">
      {{ item.uid }} >>=> {{ item?.url }}
    </div>
    <!-- action="api/Upload/doUploadImage" -->
    <a-upload
      :file-list="state.fileList"
      name="file"
      list-type="picture-card"
      accept="image/png, image/jpeg"
      :headers="{'AuthorizationToken': state.token}"
      :show-upload-list="props.multil"
      :max-count="maxCount"
      :before-upload="beforeUpload"
      :custom-request="customRequestUpload"
      @change="handleChange"
      @remove="handleRemove"
      @preview="handlePreview"
    >
      <img v-if="props.maxCount ==1 && props.multil == false" :src="state.imageUrl" alt="avatar" class="upload-image">
      <div v-else>
        <span v-if="(props.maxCount ==1 || state.fileList.length < props.maxCount)">
          <loading-outlined v-if="state.loading" />
          <plus-outlined v-else />
          <div class="upload-text">上传</div>
        </span>
      </div>
    </a-upload>
    <a-modal :visible="state.previewVisible" title="预览图片 Preview " :footer="null" @cancel="handleModelCancel">
      <img alt="example" style="width: 100%" :src="state.imageUrl">
    </a-modal>
  </div>
</template>
<script setup>
import axios from '@/core/utils/AxiosUpload'
import { reactive, watch } from 'vue'
import { message } from 'ant-design-vue'
import { useStore } from 'vuex'
import { uuid } from '@/core/utils/Common'
const store = useStore()
const props = defineProps({
  modelValue: {type: Object, default:()=> {return []} },
  value: {type: String, default: ''},
  maxSize: {type: Number, default: null},  // 文件大小（单位: M)
  maxCount: {type: Number, default: 1},  // 文件数量
  multil: {type: Boolean, default: false} // 开启上传多个
})

// const emits = defineEmits(['update:modelValue', 'update:value' ])
//
const state = reactive({
  loading:false,
  token: store.state.auth.ACCESS_TOKEN,
  imageUrl: null,
  fileList: []
})
// watch(() => [props.a, state.b], (newValue, oldValue) => {
//   if(oldValue[0]!=newValue[0]) {
//     state.a= newValue[0]
//     state.c= newValue[1]
//   }
// })

//
watch(()=>props.value, (newValue, oldValue)=>{
  if(oldValue != newValue){
    let img =[{ 'uid': uuid(), 'name': 'image.png', 'status': 'done', 'url': newValue }]
    state.fileList = img
    state.imageUrl = newValue
  }
})

// 上传限制图片类型、大小、以及宽高尺寸
const beforeUpload= (file, fileList)=>{
  console.log(file)
  if(props.maxSize && (file.size /(1024*1024) > props.maxSize)){
    fileList.splice(fileList.indexOf(file),1)
    message.error('上传图片不能大于 '+props.maxSize+ 'm.')
    return false
  }
  state.fileList.forEach(item=> alert(item.name +'  >>  '+ file.name))
  // 选择过的图片提示
  if(state.fileList.some(item=> file.name == item.name)){
    fileList.splice(fileList.indexOf(file),1)
    message.error('该图片名称刚刚已经选择过。')
    return false
  }
  // 图片宽高
  // return new Promise((resolve, reject) => {
  //   let w = 0, h = 0
  //   const reader = new FileReader()
  //   reader.readAsDataURL(file)
  //   reader.onload = () => {
  //     const image = new Image()
  //     image.src = reader.result
  //     image.onload = () => {
  //       w = image.width, h = image.height
  //       if (w <= 550 && h <= 510) {
  //         // 图片尺寸上限为550
  //         return resolve(true)
  //       }
  //       message.error('图片尺寸上限为550*510')
  //       return reject(false)
  //     }
  //   }
  // })
}

// 上传变化状态
const handleChange = async (info)=>{
  //console.dir(info.fileList)
  const { file, fileList } = info
  if (file.status === 'uploading') {
    state.loading = true
    return
  }
  // 成功处理
  if (file.status === 'done') {
    const { response } = file
    if(response.code == 0){
      let base64Url = await getBase64(file.originFileObj)
      // console.info(base64Url)
      state.imageUrl = base64Url
      fileList[fileList.length -1] = file
      state.loading = false
    }else {
      state.loading = false
      file.status = 'error'
      message.error('上传失败:' + response.msg)
    }
    
  }
  // 失败处理
  if (file.status === 'error') {
    state.loading = false
    message.error('上传失败')
  }
}

// 读图片的BASE64字符串
const getBase64= (file) =>{
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = error => reject(error)
  })
}

// 册除文件
const handleRemove = (args)=>{
  console.info('Remove::' +JSON.stringify(args))
}

// 预览图片
const handlePreview = (file)=>{
  state.imageUrl = file.url | state.imageUrl
  state.previewVisible = true
}

// 关闭预览图片
const handleModelCancel = () => {
  state.previewVisible = false
}

// 自定义上传
const customRequestUpload = (options)=>{
  const _file = options.file
  console.info('---------file--------------')
  console.log(_file)
  const formData = new FormData() //创建一个FormData对象
  formData.append('file', _file)
  // 上传
  axios.post('/api/Upload/doUploadImage', formData, {
    onUploadProgress: progressEvent => {
      const progress = Math.round(progressEvent.loaded / progressEvent.total * 100)
      console.log('上传进度：' + progress + '%')
      _file.precent = progress
    }
  }).then( res => {
    if(res.code == 0) {
      state.fileList.forEach(file=>{
        file.status = 'done'
      })
      message.success('上传成功【upload successfully.】')
    }else {
      message.error('失败::'+ res.msg)
    }
  }).catch(() => {
    message.error('上传失败[upload failed.]')
  }).finally(()=>{
    state.uploading = false
  })
}
</script>
<style>
.ant-upload.ant-upload-select-picture-card { overflow: hidden;}
.upload-image {width: 100%; width: 100%;}
.upload-text {
  margin-top: 8px;
  color: #666;
}
</style>